<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input v-model="uname" type="text" />
    </div>
    <div>
      <span>年龄:</span>
      <input v-model="uage" type="number" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="usex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add(num)">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="edit(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      arr: [
        {
          name: "Tom",
          age: 18,
          sex: "男",
        },
        {
          name: "jerry",
          age: 15,
          sex: "女",
        },
        {
          name: "jack",
          age: 20,
          sex: "男",
        },
        {
          name: "rose",
          age: 18,
          sex: "女",
        },
      ],
      uname: "",
      uage: "",
      usex: "",
      isOk: true,
      num: "",
    };
  },
  methods: {
    add(index) {
      if (!this.uname || this.uage <= 0 || !this.usex) {
        return alert("任一项不能为空！");
      }
      if (this.isOk) {
        this.arr.push({
          name: this.uname,
          age: this.uage,
          sex: this.usex,
        });
      } else {
        this.arr[index].name = this.uname;
        this.arr[index].age = this.uage;
        this.arr[index].sex = this.usex;
        this.isOk = true;
      }
      this.uname = "";
      this.uage = "";
      this.usex = "";
    },
    del(index) {
      this.arr.splice(index, 1);
    },
    edit(index) {
      this.uname = this.arr[index].name;
      this.uage = this.arr[index].age;
      this.usex = this.arr[index].sex;
      this.num = index;
      this.isOk = false;
    },
  },
};
</script>
